package com.Test.com;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;

public class ClientReceiveRunnable implements Runnable{
    private Socket socket;
    private HashMap<String,String>friendMap;
    ArrayList<Boolean> threadState;
    public ClientReceiveRunnable(Socket socket, HashMap<String, String> friendMap,ArrayList<Boolean>threadState) {
        this.socket = socket;
        this.friendMap = friendMap;
        this.threadState=threadState;
    }

    @Override
    public void run() {
        try {
            System.out.println("客户端开始接收消息!");
            ObjectInputStream objectInputStream=new ObjectInputStream(socket.getInputStream());
            SerialiableMessage serialiableMessage;
            while ((serialiableMessage=(SerialiableMessage)objectInputStream.readObject())!=null){
                if(threadState.get(0).equals(false)){
                    objectInputStream.close();
                    break;
                }
                if (serialiableMessage.getMessage().equals("accountList")) {
                    if (serialiableMessage.getReceiveUserName().equals("login")) {
                        friendMap.put(serialiableMessage.getSendUserNmae(),serialiableMessage.getSendIp());
                    }else {
                        friendMap.remove(serialiableMessage.getSendUserNmae());
                    }
                }else {
                    System.out.println("收到消息!");
                    System.out.println("[from]  "+serialiableMessage.getSendUserNmae());
                    System.out.println("[message]:  "+serialiableMessage.getMessage());
                }
            }
        } catch (IOException e) {
        } catch (ClassNotFoundException e) {
        }
    }
}
